package com.meilai.project.service.finance.supplier.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilai.project.dto.finance.supplier.SupplierManageDTO;
import com.meilai.project.entity.finance.supplier.Supplier;
import com.meilai.project.exception.CommonException;
import com.meilai.project.mapper.finance.supplier.SupplierManageMapper;
import com.meilai.project.service.finance.supplier.SupplierManageService;
import com.meilai.project.vo.finance.supplier.SupplierVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @author ykb
 * @date 2022/2/12 20:19
 */
@Service
@Log4j2
public class SupplierManageServiceImpl extends ServiceImpl<SupplierManageMapper, Supplier> implements SupplierManageService {


    @Override
    public Page<SupplierVO> selectPageList(Integer current_page, Integer page_size, SupplierManageDTO searchDTO) {
        Page<SupplierVO> page = new Page<>(current_page, page_size);
        List<SupplierVO> list = baseMapper.selectPageList(page, searchDTO);

        return page.setRecords(list);
    }

    @Override
    public List<SupplierVO> selectList(SupplierManageDTO searchDTO) {
        return baseMapper.selectPageList(searchDTO);
    }


    @Override
    @Transactional
    public Boolean addOne(SupplierManageDTO dto) {
        List<Supplier> list = list(new QueryWrapper<Supplier>().isNull("deleted_at").eq("name", dto.getName()));
        if (list != null && list.size() > 0) throw new CommonException("该供应商名称已存在");
        Supplier supplier = new Supplier();
        BeanUtils.copyProperties(dto, supplier);

        return save(supplier);
    }


    @Override
    @Transactional
    public Boolean editOne(SupplierManageDTO dto) {
        Supplier temp = getById(dto.getId());
        if (temp == null) return false;
        Supplier supplier = new Supplier();
        BeanUtils.copyProperties(dto, supplier);
        return updateById(supplier);
    }


    @Override
    @Transactional
    public Boolean delete(Long id) {
        LocalDateTime now = LocalDateTime.now();
        Supplier temp = getById(id);
        if (temp == null) return false;
        Supplier supplier = new Supplier();
        supplier.setId(id);
        supplier.setDeleted_at(now);
        return updateById(supplier);
    }

}
